//
//  PinterestHome.swift
//  SwiftUILean
//
//  Created by wyknmjj on 2024/5/14.
//

import SwiftUI

struct PinterestHome: View {
    var coordinator:PinterestCoordinator = .init()
    var body: some View {
        if coordinator.isLoading {
            Text("Loading...")
        }else{
            switch(coordinator.result){
            case .error(let e):
                Text("Error \(e)")
            case .success(data: let list):
                contentView(list)
            }
        }
    }
    
    @ViewBuilder
    func contentView(_ list:[PinterestItem]) -> some View{
        ScrollView(.vertical){
            LazyVStack(alignment: .leading, spacing: 15){
                Text("Welcome Back!")
                    .font(.largeTitle.bold())
                    .padding(.vertical,10)
                
                LazyVGrid(columns: Array(repeating: GridItem(spacing: 10), count: 2), spacing: 10) {
                    ForEach(list){post in
                        PostCardView(post)
                    }
                }
            }.padding(15)
            .background(ScrollViewExtractor(result: {
                coordinator.scrollView=$0
            }))
        }
        .opacity(coordinator.hideRootView ? 0 : 1)
        .scrollDisabled(coordinator.hideRootView)
        .allowsTightening(!coordinator.hideRootView)
        .overlay{
//            if let animationLayer = coordinator.animationLayer {
//                Image(uiImage: animationLayer)
//                    .ignoresSafeArea()
//                    .opacity(0.5)
//            }
            PinterestDetail()
                .environment(coordinator)
                .allowsHitTesting(coordinator.hideLayer)
        }
    }
    
    @ViewBuilder
    func PostCardView(_ post:PinterestItem) -> some View {
        GeometryReader{
            let frame = $0.frame(in: .global)
            PinterestHeroImageView(post: post)
                .clipShape(.rect(cornerRadius: 10))
                .contentShape(.rect(cornerRadius: 10))
                .onTapGesture {
                    coordinator.toggleView(show: true, frame: frame, post: post)
                }
        }.frame(height: 180)
    }
}

#Preview {
    PinterestHome()
}
